﻿package com.util.asyncPost;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.os.Message;
import android.util.Log;

import com.google.gson.JsonElement;

class AsyncRequestThread extends Thread {
	private static final String TAG = "AsyncClient";

	private HttpClient mHttpClient;
	private AsyncHandler mHandler;
	private String requestUrl;
	public ArrayList<BasicNameValuePair> pairParams = new ArrayList<BasicNameValuePair>();

	public AsyncRequestThread(HttpClient client, AsyncHandler handler) {
		mHttpClient = client;
		mHandler = handler;
	}

	public void addRequestParams(String key, String value) {
		BasicNameValuePair param = new BasicNameValuePair(key, value);
		pairParams.add(param);
	}

	public void setRequestUrl(String url) {
		requestUrl = url;
	}

	public void startRequest() {
		this.start();
	}

	@Override
	public void run() {
		procressRequest();
	}

	private void procressRequest() {
		String responseContent = null;
		try {
			HttpPost post = getHttpPost();
			HttpResponse response = mHttpClient.execute(post);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK)
				responseContent = EntityUtils.toString(response.getEntity(),
						HTTP.UTF_8);
			else
				sendFailMsg(mHandler, "Response status code " + statusCode);
		} catch (ClientProtocolException e) {
			sendExceptionMsg(mHandler, e);
		} catch (IOException e) {
			sendExceptionMsg(mHandler, e);
		} catch (Exception e) {
			sendExceptionMsg(mHandler, e);
		}

		Log.d(TAG, "all responseContent = " + responseContent);
		if (responseContent == null || responseContent.trim().equals(""))
			sendExceptionMsg(mHandler, new Exception("Entity is NULL!!"));
		else {
			// 到上面为止，服务器返回的内容都已经获取到了
			// 接下来就是解析返回的内容了
			analysisResponse(responseContent);
		}

	}

	private HttpPost getHttpPost() throws Exception {
		if (requestUrl == null)
			throw new Exception("url is NULL!");
		HttpPost post = new HttpPost(requestUrl);
		if (pairParams != null)
			post.setEntity(new UrlEncodedFormEntity(pairParams, HTTP.UTF_8));
		try {
			Log.d(TAG, "request url = " + post.getURI() + ", entity = "
					+ EntityUtils.toString(post.getEntity(), HTTP.UTF_8));
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return post;
	}

	public void analysisResponse(String responseContent) {
	//TODO 具体解析这个返回值。
	//这里就不解析，直接返回null了。
		sendSuccessWithBodyMsg(mHandler, null);
	}

	private void sendExceptionMsg(AsyncHandler httpHandler, Exception e) {
		Message msg = Message.obtain();
		msg.what = AsyncHandler.HTTP_MSG_EXCEPTION;
		msg.obj = e;
		httpHandler.sendMessage(msg);
	}

	private void sendSuccessWithBodyMsg(AsyncHandler httpHandler,
			JsonElement responseJSONObject) {
		Message msg = Message.obtain();
		msg.what = AsyncHandler.HTTP_MSG_SUCCESS;
		msg.obj = responseJSONObject;
		httpHandler.sendMessage(msg);
	}

	private void sendFailMsg(AsyncHandler httpHandler, String failMsg) {
		Message msg = Message.obtain();
		msg.what = AsyncHandler.HTTP_MSG_FAIL;
		msg.obj = failMsg;
		httpHandler.sendMessage(msg);
	}

}
